package com.javasee.common.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.support.AopUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Project Name:
 * File Name   :
 * Package Name:
 *
 * @author : xinyanfei
 * @date :
 * Copyright (c) , 京东商城  All Rights Reserved.
 */

@Aspect
@Component
public class LoggerAop {

    @Pointcut("@annotation(com.javasee.common.annotation.MyLogger)")
    public void pointcut()
    {}

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) throws Exception
    {
        printMethod(joinPoint, "[前置通知Before]");
    }

    @After("pointcut()")
    public void after(JoinPoint joinPoint) throws NoSuchMethodException {
        printMethod(joinPoint, "[后置通知After]");
    }

    private void printMethod(JoinPoint joinPoint, String name) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> clazz = joinPoint.getTarget().getClass();
        Method method = clazz.getMethod(signature.getName(), signature.getParameterTypes());
        System.out.printf("[MethodLogAspect]切面 %s 打印 -> [className]:%s  ->  [methodName]:%s  ->  [methodArgs]:%s%n", name, clazz.getName(), method.getName(), Arrays.toString(joinPoint.getArgs()));

        Class<?>[] targets = AopUtils.getTargetClass(joinPoint.getTarget()).getInterfaces();
        for (Class<?> clazz1 : targets) {
            System.out.printf("[targets]切面打印 -> [className]:%s  ->  [getInterfaces]:%s  ", clazz1.getName(), Arrays.toString(clazz.getInterfaces()));

        }
    }
}
